package com.lhh.springcommon.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.lhh.springcommon.exception.CustomException;
import com.lhh.springcommon.utils.CodeEnum;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 阿里云oss 上传工具类
 * @author 李厚航
 */
public class Oss {

    /**
     * 上传文件
     * @return
     */
    public static Map<String,String> policy(OSS ossClient,String bucket,String endpoint,String accessId,String prefix){
        //host 格式为bucket.endpoint
        String host = "https://" + bucket + "." + endpoint;
        //callbackUrl 为传回调服务器的url，请修改成自己的信息
//        String callbackUrl = "http://88.88.88.88:8888";
        //用户上传文件时的指定前缀（oss文件夹目录）
        String dir = prefix + "/";
        Map<String, String> respMap = null;
        try {
            long expireTime = 30;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            // PostObject请求最大可支持的文件大小为5 GB，即CONTENT_LENGTH_RANGE为5*1024*1024*1024。
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes(StandardCharsets.UTF_8);
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = ossClient.calculatePostSignature(postPolicy);

            respMap = new LinkedHashMap<>();
            respMap.put("accessId", accessId);
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", dir);
            respMap.put("host", host);
            respMap.put("expire", String.valueOf(expireEndTime / 1000));
        }catch (Exception e){
            throw new CustomException(CodeEnum.FILE_UPLOAD_FAILED);
        }
        return respMap;
    }

}
